package com.tanhua.db.api;

import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.db.mapper.SoundMapper;
import com.tanhua.db.mapper.SoundTimesMapper;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.model.pojo.Sound;
import com.tanhua.model.pojo.SoundTimes;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Random;

@DubboService
public class SoundApiImpl implements SoundApi {

    @Autowired
    private SoundMapper soundMapper;

    @Autowired
    private SoundTimesMapper soundTimesMapper;

    //保存或者修改数据
    @Override
    public String saveOrUpdate(String soundUrl, Long userId) throws Exception {
        //1.先查询次数表中是否有次数
        SoundTimes times = soundTimesMapper.selectOne(Wrappers.lambdaQuery(SoundTimes.class).eq(SoundTimes::getUserId, userId));
        if (StringUtils.isEmpty(times)){
            //如果次数表中是空则插入数据
            SoundTimes soundTimes = new SoundTimes();
            soundTimes.setUserId(userId);
            soundTimesMapper.insert(soundTimes);
        }else {
            if (times.getSendtimes()>0){
                //如果有次数 则直接保存数据到语音表
                Sound retSound = new Sound();
                retSound.setUserId(userId);
                retSound.setSoundUrl(soundUrl);
                soundMapper.insert(retSound);
                //保存数据到语音次数表
                times.setSendtimes(times.getSendtimes()-1);
                soundTimesMapper.updateById(times);
            }else {
                return "今日次数已经用完,明天再来";
            }
        }
        return null;
    }

    //随机挑选一条语音
    @Override
    public Sound getOne() {
        //查询所有数据
        List<Sound> sounds = soundMapper.selectList(null);
            Random random = new Random();
            int nextInt = random.nextInt(sounds.size());
            return sounds.get(nextInt);
    }

    //删除语音信息
    @Override
    public void delete(Sound sound) {
        soundMapper.deleteById(sound);
    }
}
